package cn.nexd.collector.bean;

import android.bluetooth.BluetoothDevice;

import java.util.List;

/**
 * Created by codngfish on 16/6/1.
 */
abstract class BeaconCollectorStoryStrategy {

    protected void process(BluetoothDevice device, int rssi, byte[] scanRecord, long timestamp) {

        int startByte = 2;

        while (startByte <= 5) {
            //Identifies an iBeacon
            //Identifies correct data length
            if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && ((int) scanRecord[startByte + 3] & 0xff) == 0x15) {
                // Beacon
                handlerData(device, rssi, scanRecord, timestamp, startByte);
                break;
            }
            startByte++;
        }
    }

    abstract List<BeaconScannerResult> getBeaconScanerResults();

    abstract void handlerData(BluetoothDevice device, int rssi, byte[] scanRecord, long timestamp, int startByte);

    abstract void clear();

    protected int getMajor(int startByte, byte[] scanRecord) {
        return (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);
    }

    protected int getMinor(int startByte, byte[] scanRecord) {
        return (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);
    }

    protected String getUUID(int startByte, byte[] scanRecord) {
        byte[] uuidBytes = new byte[16];
        System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
        String hexString = bytesToHex(uuidBytes);
        return hexString.substring(0, 8) + "-" + hexString.substring(8, 12) + "-" + hexString.substring(12, 16) + "-" + hexString.substring(16, 20) + "-" + hexString.substring(20, 32);
    }

    private static final char[] hexArray = "0123456789ABCDEF".toCharArray();

    private String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

}
